import axios, { AxiosRequestConfig, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios';
import { getStoredToken, clearAuthData } from '../api/auth';

// 路由常量
const AUTH_ROUTES = {
  LOGIN: '/auth/login',
  REGISTER: '/auth/register',
  VERIFY_EMAIL: '/auth/verify-email',
};

export interface ApiResponse<T> {
  success: boolean;
  code: number;
  message: string;
  data: T;
  timestamp: string;
}

// 创建axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = getStoredToken();
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error: any) => {
    console.error('请求拦截器错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误和刷新token
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 添加调试日志
    console.log('响应拦截器收到数据:', {
      status: response.status,
      data: response.data,
      headers: response.headers
    });

    // 如果响应中包含data字段，则返回data
    return response.data;
  },
  async (error: AxiosError) => {
    if (!error.response) {
      console.error('网络错误，请检查您的网络连接');
      return Promise.reject(new Error('网络错误，请检查您的网络连接'));
    }

    const { status, data } = error.response;
    console.error('API错误:', {
      status,
      data,
      url: error.config?.url
    });

    // 处理401未授权错误 - token过期或无效
    if (status === 401) {
      // 清除认证数据
      clearAuthData();
      
      // 如果不是认证相关页面，重定向到登录页
      if (!window.location.pathname.startsWith('/auth/')) {
        // 保存当前路径，以便登录后返回
        const returnUrl = window.location.pathname;
        window.location.href = `${AUTH_ROUTES.LOGIN}?returnUrl=${encodeURIComponent(returnUrl)}`;
      }
    }

    // 处理后端返回的错误信息
    const errorMessage = (data as any)?.message || '请求失败，请稍后再试';
    console.error('API错误:', errorMessage);
    
    return Promise.reject(new Error(errorMessage));
  }
);

// 重写request的类型定义，使其返回响应数据而不是整个响应对象
export const request = instance as {
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
  patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
}; 